<template>
    <div style="height:100%">
      <div>
        <div class='content-title'>
          <div class='content-title-parent'>失物管理</div>
          /
          <div class='content-title-child'>失物上报</div>
        </div>
        <hr class='content-hr'/>
      </div>
      <!--表格筛选条件-->
      <el-row style="margin-top:10px" class='lostManaClass'>
        <el-form v-model="filterForm" ref="filterForm":inline="true">
          <el-form-item label="物品关键字：" label-width="100px">
            <el-input  style="width:160px" @keyup.native="filterForm.materialName=filterForm.materialName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" clearable  v-model.trim="filterForm.materialName"></el-input>
          </el-form-item>
          <el-form-item label="物品分类：">
            <el-select  style="width:160px" clearable  v-model="filterForm.classId" placeholder="选择物品分类">
              <el-option
                v-for="item in categoryList"
                :key="item.classId"
                :label="item.className"
                :value="item.classId">
              </el-option>
            </el-select>
          </el-form-item>
            <el-form-item label="遗失地点：" >
              <el-cascader
                clearable
                style="width:160px" 
                v-model="filterForm.airportList"
                expand-trigger="hover"
                :options="filterForm.airportNameList"
                @change="selectAirport('filterForm')"
                :props="airportProps"
              >
              </el-cascader>
          </el-form-item>
          <el-form-item label="乘坐航班号：">
            <el-input  style="width:160px" @keyup.native="filterForm.flightNumber=filterForm.flightNumber.replace(/[^\w]/g, '')"  clearable  v-model="filterForm.flightNumber"></el-input>
          </el-form-item>
          <el-form-item label="遗失时间：" label-width="100px">
            <el-date-picker
              v-model="filterForm.lostTime"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="物品状态：">
            <el-checkbox-group v-model="filterForm.goodsState">
              <el-checkbox label="未找到"></el-checkbox>
              <el-checkbox label="已找到"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="" >
            <el-button type="primary" style="background-color:#2280E9;border-color:#2280E9;width:60px;" @click="submitSearch()">查询</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!--查询表格数据-->
      <el-row>
        <el-table
          class='lostManTableClass'
          v-loading="loading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255, 255, 255, 0.8)"
          :data="filterFormFro.tableData"
          :border="true"
          :row-class-name="tableRowClassName"
          :cell-class-name="tabelCellClassName"
          :header-cell-class-name = "tableHeaderClassName"
          v-bind:style="{width: tableWidth + 'px'}">
            <el-table-column prop="index" label="序号" min-width="8%">
            </el-table-column>
            <el-table-column prop="materialName" label="物品名称"  min-width="10%">
            </el-table-column>
            <el-table-column prop="className" label="物品分类" min-width="10%">
            </el-table-column>
            <el-table-column prop="codeAirport" label="所属机场" min-width="15%">
            </el-table-column>
            <el-table-column prop="flightNumber" label="航班号" min-width="15%">
            </el-table-column>
            <el-table-column prop="terminalName" label="遗失地点" min-width="15%">
            </el-table-column>
            <el-table-column prop="address" label="详细地址"min-width="15%">
            </el-table-column>
            <el-table-column prop="lostTime" label="遗失时间" min-width="15%">
            </el-table-column>
            <el-table-column prop="state" label="状态" min-width="8%">
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDetail(scope.$index, scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!--分页-->
      <el-row>
        <div class="pagination" style="text-align:center" v-show="paginationVisible">
          <el-pagination
            @current-change="handleCurrentChange"
            background
            :current-page="filterForm.pageNum"
            :page-size="15"
            layout="total, prev, pager, next"
            :page-count="filterFormFro.totalPage">
          </el-pagination>
        </div>
      </el-row>
      <!-- 查看失物上报详情弹窗 -->
      <el-dialog title="失物详情:" :visible.sync="detailVisable"
        :modal="false"
        class="categoryManaDialog lostReportDialog"
        :closeOnClickModal="false"
        :close-on-press-escape="false"
        width="600px">
        <div class="inner">
          <div class="innerbox" style="">
            <el-form style="" v-model="detailForm" label-width="90px">
              <el-form-item label="物品名称：">
                <span>{{detailForm.materialName}}</span>
              </el-form-item>
              <el-form-item label="物品分类：">
                <span>{{detailForm.className}}</span>
              </el-form-item>
              <el-form-item label="遗失地点：">
                <span>{{detailForm.lostAddress}}</span>
              </el-form-item>
              <el-form-item label="详细地址：">
                <span>{{detailForm.address}}</span>
              </el-form-item>
              <el-form-item label="航班号：">
                <span>{{detailForm.flightNumber}}</span>
              </el-form-item>
              <el-form-item label="座位号：">
                <span>{{detailForm.seatNumber}}</span>
              </el-form-item>
              <el-form-item label="联系方式：">
                <span>{{detailForm.phoneNum}}</span>
              </el-form-item>
              <el-form-item label="上报时间：">
                <span>{{detailForm.lostTime}}</span>
              </el-form-item>
              <el-form-item label="物品特征：">
                <span>{{detailForm.describtion}}</span>
              </el-form-item>
              <el-form-item label="物品状态：">
                <el-radio-group v-model="detailForm.goodsState">
                  <el-radio label="已找到"></el-radio>
                  <el-radio label="未找到"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div style="text-align:center;margin-top:10px" class="dialog-footer">
          <el-button type="primary" @click="editLostReportFro()">保 存</el-button>
        </div>
      </el-dialog>
    </div>
</template>
<style scoped>
  .baseFee-title {
    clear:left;
    width:80px;
    float:left;
    margin-top:15px
  }
  .baseFee-content {
    float:left;
    width:216px;
    margin-top:15px
  }
</style>
<script>
import apiBus from '../../api/businessPlat/apiBus.js'
import '../../../static/css/businessPlat/common.css'
import '../../../static/css/businessPlat/lostMana.css'
import '../../../static/css/businessPlat/lostReport.css'
export default {
  created () {
    this.init()
    this.getAllClassFro()
    this.getAllTerminalFro()
    this.getLostReportListFro()
  },
  data () {
    return {
      tableWidth: '',
      addVisable: false, // 添加失物弹窗
      detailVisable: false, // 失物详情弹窗
      loading: true, // 加载是否显示
      loadingText: '正在拼命加载，请稍等......', // 加载显示内容
      categoryList: [], // 下拉框中的分类列表
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      airportProps: {
        value: 'label',
        children: 'terminals'
      },
      props: {
        value: 'label',
        children: 'cities'
      },
      filterFormFro: { // 查询获得列表
        tableData: [],
        totalPage: 2
      },
      filterForm: { // 筛选表单
        materialName: '', // 失物名称
        className: '',
        classId: '',
        terminalId: [],
        terminalName: [],
        airportName: '',
        airportId: '',
        flightNumber: '',
        lostTime: [],
        pageNum: 1,
        isDelete: '',
        airportNameList: [],
        airportList: [],
        goodsState: ['未找到', '已找到'] // 物品状态
      },
      paginationVisible: false, // 表格下方分页是否显示
      noteVisible: false,
      formLabelWidth: '30%',
      addForm: {
        materialName: '',
        classId: '',
        airportId: '',
        terminalId: '',
        address: '',
        registerTime: '',
        pickUpAirportId: '',
        pickUpTerminalId: '',
        placeId: '',
        pickUpState: ''
      },
      editVisable: false,
      editForm: {
        couponId: '',
        couponName: '',
        value: '',
        isFixed: '',
        airportName: '',
        businessName: '',
        peopleLimit: '1',
        fullUse: '',
        onlineTime: '',
        effectiveTime: '',
        expireTime: '',
        limitNum: '',
        issuedNum: '',
        issuedType: '1',
        takenNum: '',
        isDelete: ''
      },
      detailForm: {
        materialName: '',
        className: '',
        lostAddress: '',
        address: '',
        flightNumber: '',
        seatNumber: '',
        phoneNum: '',
        registerTime: '',
        describtion: '',
        goodsState: ''
      },
      deleteForm: {
        label: '',
        num: '',
        number: ''
      },
      addRules: { // 弹窗添加标签信息验证规则
      }
    }
  },
  methods: {
    /** 页面处理，数据格式处理函数 */
    // 初始化搜索数据
    init () {
      /* let end = new Date()
      let start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      this.filterForm.lostTime[0] = start
      this.filterForm.lostTime[1] = end */
      let end = new Date()
      let start = new Date()
      let hour = new Date().getHours()
      let minute = new Date().getMinutes()
      let second = new Date().getSeconds()
      start.setTime(start.getTime() - hour * 3600 * 1000 - minute * 60 * 1000 - second * 1000 - 24 * 3600 * 30 * 1000)
      end.setTime(end.getTime() - hour * 3600 * 1000 - minute * 60 * 1000 - second * 1000)
      this.filterForm.lostTime[0] = start
      this.filterForm.lostTime[1] = end
    },
    // 分页页面跳转时
    handleCurrentChange (val) {
      this.filterForm.pageNum = val
      this.getLostReportListFro()
    },
    // 根据后台发的数据显示状态样式
    tabelCellClassName ({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 7) {
        if (row.goodsState === '未找到') {
          return 'cellClass'
        }
      }
    },
    submitSearch () {
      this.filterForm.pageNum = 1
      this.getLostReportListFro()
    },
    // 处理后台发来的数据以显示在下拉框中（主要针对机场和航站楼，使其可以二级联动选择）
    setDropdown (testAirport, form) {
      let parentIdList = []
      let totalList = []
      for (let i = 0; i < testAirport.length; i++) {
        if (parentIdList.indexOf(testAirport[i].airportId) === -1) {
          parentIdList.push(testAirport[i].airportId)
          totalList.push({
            label: testAirport[i].figureThree + ' ' + testAirport[i].airportName,
            airportId: testAirport[i].airportId,
            terminals: []
          })
        }
      }
      for (let i = 0; i < totalList.length; i++) {
        testAirport.forEach((item) => {
          if (item.airportId === totalList[i].airportId) {
            totalList[i].terminals.push({
              label: item.terminalName,
              terminalId: item.terminalId
            })
          }
        })
      }
      if (form === 'filterForm') {
        for (let i = 0; i < totalList.length; i++) {
          totalList[i].terminals.push({
            label: '全部',
            terminalId: ''
          })
        }
      }
      this[form].airportNameList = totalList
    },
    // 将时间从时间戳转化为字符串显示
    formatDateFro (now) {
      var year = now.getFullYear()
      var month = now.getMonth() + 1
      month = month < 10 ? '0' + month : month
      var date = now.getDate()
      date = date < 10 ? ('0' + date) : date
      var hour = now.getHours()
      hour = hour < 10 ? ('0' + hour) : hour
      var minute = now.getMinutes()
      minute = minute < 10 ? ('0' + minute) : minute
      var second = now.getSeconds()
      second = second < 10 ? ('0' + second) : second
      return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
    },
    // 将时间转化为字符串(filterForm)
    formatDayFro (now) {
      var year = now.getFullYear()
      var month = now.getMonth() + 1
      month = month < 10 ? '0' + month : month
      var date = now.getDate() + 1
      date = date < 10 ? ('0' + date) : date
      var hour = now.getHours()
      hour = hour < 10 ? ('0' + hour) : hour
      var minute = now.getMinutes()
      minute = minute < 10 ? ('0' + minute) : minute
      var second = now.getSeconds()
      second = second < 10 ? ('0' + second) : second
      return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
    },
    // 下拉框选择机场及航站楼
    selectAirport (Form) {
      for (let i = 0; i < this[Form].airportNameList.length; i++) {
        this[Form].terminalId = []
        if (this[Form].airportNameList[i].label === this[Form].airportList[0]) {
          this[Form].airportId = this[Form].airportNameList[i].airportId
          this[Form].airportName = this[Form].airportNameList[i].label
          for (let m = 0; m < this[Form].airportNameList[i].terminals.length; m++) {
            if (this[Form].airportList[1] === this[Form].airportNameList[i].terminals[m].label && this[Form].airportList[1] !== '全部') {
              this[Form].terminalId.push(this[Form].airportNameList[i].terminals[m].terminalId)
              this[Form].terminalName.push(this[Form].airportNameList[i].terminals[m].label)
              break
            } else if (this[Form].airportList[1] === '全部') {
              if (this[Form].airportNameList[i].terminals[m].label !== '全部') {
                this[Form].terminalId.push(this[Form].airportNameList[i].terminals[m].terminalId)
                this[Form].terminalName.push(this[Form].airportNameList[i].terminals[m].label)
              }
            }
          }
          break
        }
      }
    },
    setDetailFro () {
      this.editVisable = false
      this.$message.success('失物详情编辑成功')
    },
    changeCategory () {
      this.$message.error('分类选择：' + this.filterForm.category)
    },
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    // 点击表格中详情按钮
    handleDetail (index, row) {
      let data = this.filterFormFro.tableData[index]
      this.detailForm.materialName = data.materialName
      this.detailForm.className = data.className
      this.detailForm.address = data.address
      this.detailForm.flightNumber = data.flightNumber
      this.detailForm.seatNumber = data.seatNumber
      this.detailForm.phoneNum = data.phoneNum
      this.detailForm.lostTime = this.formatDateFro(new Date(data.lostTime))
      this.detailForm.describtion = data.describtion
      this.detailForm.pickUpState = data.pickUpState
      this.detailForm.materialId = data.materialId
      this.detailForm.goodsState = data.state
      if (data.figureThree) {
        this.detailForm.lostAddress = data.figureThree + data.airportName + ' ' + data.terminalName
      } else {
        this.detailForm.lostAddress = data.tetradCode + data.airportName + ' ' + data.terminalName
      }
      this.detailVisable = true
    },
    handleDelete (index, row) {
      this.deleteForm.couponName = row.couponName
      this.deleteForm.couponId = row.couponId
      this.noteVisible = true
    },
    cancleEdit (formName) {
      this.resetError(formName)
      this.editVisable = false
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    setDeleteFro () {
      this.noteVisible = false
      this.$message.success('优惠券<' + this.deleteForm.couponName + '>已删除')
    },
    // 从后台查询所有航站楼
    getAllTerminalFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'airportService_v1'
        }),
        body: JSON.stringify({})
      }
      apiBus.getAllTerminal(para).then(res => {
        let terminalList = []
        if (res.data.body.result === 1000) {
          terminalList = res.data.body.content.list
          this.setDropdown(terminalList, 'filterForm')
          this.setDropdown(terminalList, 'addForm')
          this.setDropdown(terminalList, 'editForm')
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 查询电商标签管理处的电商分类下拉菜单的显示接口
    getAllClassFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'lostMeterialService_v1'
        }),
        body: JSON.stringify({})
      }
      apiBus.getLostCategoryList(para).then(res => {
        this.categoryList = []
        if (res.data.body.result === 1000) {
          this.categoryList = res.data.body.content.list
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 向后台发送编辑失物上报状态接口
    editLostReportFro () {
      this.loadingText = '正在拼命加载，请稍等...'
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'placeService_v1'
        }),
        body: JSON.stringify({
          materialId: this.detailForm.materialId,
          state: this.detailForm.goodsState
        })
      }
      apiBus.editLostReport(para).then(res => {
        this.loading = false
        if (res.data.body.result === 1000) {
          this.$message.success('成功保存失物上报信息！')
          this.detailVisable = false
          this.filterForm.pageNum = 1
          this.getLostReportListFro()
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    /** 向后台发送请求失物列表接口 */
    getLostReportListFro () {
      this.loading = true
      this.filterFormFro.tableData = []
      let terminalId = ''
      let endTime = null
      let startTime = null
      let goodsState = ''
      if (this.filterForm.lostTime && this.filterForm.lostTime.length > 0) {
        endTime = this.formatDayFro(this.filterForm.lostTime[1])
        startTime = this.formatDateFro(this.filterForm.lostTime[0])
      }
      this.filterForm.terminalId.length > 1 ? terminalId = '' : terminalId = parseInt(this.filterForm.terminalId[0])
      this.filterForm.goodsState.length > 0 ? goodsState = this.filterForm.goodsState : goodsState = null
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'placeService_v1'
        }),
        body: JSON.stringify({
          flightNumber: this.filterForm.flightNumber,
          materialName: this.filterForm.materialName,
          classId: parseInt(this.filterForm.classId),
          airportId: parseInt(this.filterForm.airportId),
          terminalId: terminalId,
          startTime: startTime,
          endTime: endTime,
          pageNum: parseInt(this.filterForm.pageNum),
          states: goodsState
        })
      }
      console.log('getLostReportList')
      console.log(para)
      apiBus.getLostReportList(para).then(res => {
        this.loading = false
        console.log('getLostReportList回参：')
        console.log(res)
        if (res.data.body.result === 1000) {
          if (res.data.body.content.list.length > 0) {
            this.$message.success('成功提取失物上报信息！')
            let resData = res.data.body.content.list
            this.filterFormFro.tableData = resData
            for (let i = 0; i < resData.length; i++) {
              this.filterFormFro.tableData[i].index = (parseInt(this.filterForm.pageNum) - 1) * 15 + i + 1
              this.filterFormFro.tableData[i].goodsState = resData[i].state
              this.filterFormFro.tableData[i].terminalName = resData[i].terminalName
              this.filterFormFro.tableData[i].lostTime = this.formatDateFro(new Date(this.filterFormFro.tableData[i].lostTime))
              if (this.filterFormFro.tableData[i].figureThree) {
                this.filterFormFro.tableData[i].codeAirport = resData[i].figureThree + ' ' + resData[i].airportName
              } else {
                this.filterFormFro.tableData[i].codeAirport = resData[i].tetradCode + ' ' + resData[i].airportName
              }
            }
            this.filterFormFro.totalPage = res.data.body.content.allPages
            this.filterFormFro.totalPage > 1 ? this.paginationVisible = true : this.paginationVisible = false
          } else {
            this.paginationVisible = false
            this.$message.warning('没有相关失物上报信息')
          }
        } else {
          this.paginationVisible = false
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.paginationVisible = false
        this.loading = false
        this.$message.error(error)
      })
    }
  },
  mounted () {
    this.tableWidth = document.body.scrollWidth - 259 - 20
  }
}
</script>